package com.itheima.canal.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZJ
 */
@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 商品上架,下架监听
     * @param eventType
     * @param rowData
     */
    @ListenPoint(schema = "changgou_goods", table = "tb_spu")
    public void goodsUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        //获取更改前的数据封装称Map集合
        Map<String, String> oldDate = new HashMap<>();
        rowData.getBeforeColumnsList().forEach((c) -> oldDate.put(c.getName(), c.getValue()));

        //获取更改后的数据封装Map集合
        Map<String, String> newDate = new HashMap<>();
        rowData.getAfterColumnsList().forEach((c) -> newDate.put(c.getName(), c.getValue()));

        //获取商品上下架状态由"0"->"1"
        if ("0".equals(oldDate.get("is_marketable"))&&"1".equals(newDate.get("is_marketable"))){
            //将spuIdRabbitMQConfig发送到rabbitMQ
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE, "", newDate.get("id"));
        }

        //获取商品上下架状态由"1"->"0"
        if ("1".equals(oldDate.get("is_marketable"))&&"0".equals(newDate.get("is_marketable"))){
            //将spuIdRabbitMQConfig发送到rabbitMQ
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE, "", newDate.get("id"));
        }

        //获取商品审核架状态由"0"->"1"
        if ("0".equals(oldDate.get("status"))&&"1".equals(newDate.get("status"))){
            //将spuIdRabbitMQConfig发送到rabbitMQ
            rabbitTemplate.convertAndSend(RabbitMQConfig.PAGE_CREATE_EXCHANGE, "", newDate.get("id"));
        }
    }




}
